<template>
  <div class="main-content no-padding">
    <div class="container-fluid">

      <div class="panel">
        <div class="panel-header" style="height: 30px">
          <p class="panel-title pull-left">添加 Fetcher</p>
        </div>
        <div class="panel-body">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="metric mysql" @click="showMySQLDialog">
                <p>
                  <span class="number">MySQL</span>
                  <span class="title">MySQL FETCHER</span>
                </p>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="metric mongodb" @click="showMongoDBDialog">
                <p>
                  <span class="number">MongoDB</span>
                  <span class="title">MongoDB 数据源</span>
                </p>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div class="panel">
        <div class="panel-body">
          <el-row>
            <el-col :span="14" :offset="2">
              <el-input placeholder="编码或名称" v-model="searchText" class="input-with-select">
                <template #append>
                  <el-button icon="el-icon-search" @click="search"></el-button>
                </template>
              </el-input>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="panel">
        <el-table
          :data="tableData"
          stripe
          style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <pre>
                {{ props.row.data }}
              </pre>
            </template>
          </el-table-column>
          <el-table-column
            width="50px"
            label="ID"
            prop="id">
          </el-table-column>
          <el-table-column
            :formatter="formatterType"
            width="100px"
            label="type"
            prop="type">
          </el-table-column>
          <el-table-column
            width="200px"
            label="名称"
            prop="name">
          </el-table-column>
          <el-table-column
            label="数据源datasource"
            prop="datasource">
          </el-table-column>
          <el-table-column
            label="预计执行时长(毫秒)"
            prop="estimatedExecutionTime">
          </el-table-column>
          <el-table-column
            label="description"
            prop="description">
          </el-table-column>
          <el-table-column
            width="200px"
            label="创建时间"
            prop="createTime">
          </el-table-column>
          <el-table-column
            width="200px"
            label="更新时间"
            prop="updateTime">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100">
            <template #default="scope">
              <el-button type="text" size="small">编辑</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-model:current-page="page.currentPage"
          :page-sizes="[10, 20, 30, 40]"
          v-model:page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          v-model:total="page.total">
        </el-pagination>
      </div>

      <el-dialog
        :title="dialogAddFetcherTitle"
        v-model="dialogAddFetcherVisible"
        width="50%">
        <el-form label-position="left" label-width="150px" :model="fetcherConfig">
          <el-form-item label="名称">
            <el-input v-model="fetcherConfig.name" placeholder="一个名称，全局唯一，最好是英文"></el-input>
          </el-form-item>
          <el-form-item label="预计执行时间(毫秒)">
            <el-input-number :min="1" v-model="fetcherConfig.estimatedExecutionTime"
                             placeholder="预计执行时间(毫秒)"></el-input-number>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="fetcherConfig.description"></el-input>
          </el-form-item>
          <el-form-item label="数据源">
            <el-select v-model="fetcherConfig.datasource" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in datasources"
                :key="item.id"
                :label="item.name"
                :value="item.name">
                <span style="float: left">{{ item.name }}</span>
                <span
                  style="max-width: 350px;float: right; color: #8492a6; font-size: 13px; overflow:hidden;text-overflow: ellipsis;">{{
                    item.description
                  }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="数据源">
            <el-select v-model="fetcherConfig.defaultFetchMethod" placeholder="请选择" style="width: 100%">
              <el-option :key="1" label="单次查询" :value="1"></el-option>
              <el-option :key="2" label="批量查询" :value="2"></el-option>
            </el-select>
          </el-form-item>

          <div v-show="fetcherConfig.type === 1">
            <!-- http 操作 -->
            <el-form-item label="url">
              <el-input v-model="httpExpansionConfig.url" placeholder="http url（全路径）"></el-input>
            </el-form-item>
            <el-form-item label="method">
              <el-select v-model="httpExpansionConfig.method" placeholder="请选择">
                <el-option label="GET" value="GET"></el-option>
                <el-option label="POST" value="POST"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="headers">
              <el-row v-for="(header, index) in httpExpansionConfig.headers">
                <el-col class="line" :span="3">header key : &nbsp;</el-col>
                <el-col :span="7">
                  <el-input placeholder="header key" v-model="header.key" style="width: 100%;"></el-input>
                </el-col>
                <el-col class="line" :span="3">header value : &nbsp;</el-col>
                <el-col :span="7">
                  <el-input placeholder="header value" v-model="header.value" style="width: 100%;"></el-input>
                </el-col>
                <el-col :span="4">
                  &nbsp;
                  <el-button type="primary" icon="el-icon-plus" circle @click="addHttpHeader(index)"></el-button>
                  <el-button type="danger" icon="el-icon-delete" circle @click="removeHttpHeader(index)"></el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="http auth">
              <el-row>
                <el-col class="line" :span="3">username : &nbsp;</el-col>
                <el-col :span="7">
                  <el-input placeholder="username" v-model="httpExpansionConfig.httpAuth.username"
                            style="width: 100%;"></el-input>
                </el-col>
                <el-col class="line" :span="3">password : &nbsp;</el-col>
                <el-col :span="7">
                  <el-input placeholder="password" v-model="httpExpansionConfig.httpAuth.password"
                            style="width: 100%;"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </div>

          <div v-show="fetcherConfig.type === 2">
            <!-- MySQL 操作 -->
            <el-form-item label="table">
              <el-input v-model="mysqlExpansionConfig.table" placeholder="表名"></el-input>
            </el-form-item>
            <el-form-item label="查询字段">
              <table class="mytable">
                <tr>
                  <th>#</th>
                  <th>映射出变量名</th>
                  <th>数据库原始字段名</th>
                  <th>操作</th>
                </tr>
                <tr v-for="(item, index) in mysqlExpansionConfig.columnItems">
                  <td>{{ index }}</td>
                  <td>
                    <el-input placeholder="数据库原始字段名" v-model="item.alias" style="width: 100%;"></el-input>
                  </td>
                  <td>
                    <el-input placeholder="映射出变量名" v-model="item.column" style="width: 100%;"></el-input>
                  </td>
                  <td>
                    <el-button type="primary" icon="el-icon-plus" circle @click="addMySQLField(index)"></el-button>
                    <el-button type="danger" icon="el-icon-delete" circle @click="removeMySQLField(index)"></el-button>
                  </td>
                </tr>
              </table>
            </el-form-item>
            <el-form-item label="查询表达式">
              <el-input v-model="mysqlExpansionConfig.condition" placeholder="where 条件表达式"></el-input>
            </el-form-item>
            <el-form-item label="查询数量（limit）">
              <el-input-number v-model="mysqlExpansionConfig.limit" :min="-1" :max="65535"
                               label="查询数量"></el-input-number>
            </el-form-item>
          </div>
          <div v-show="fetcherConfig.type === 4">
            <!-- MongoDB 操作 -->
            <el-form-item label="collection">
              <el-input v-model="mongoDBExpansionConfig.collection" placeholder="collection 名称"></el-input>
            </el-form-item>
            <el-form-item label="查询表达式">
              <el-input v-model="mongoDBExpansionConfig.condition" placeholder="find 条件表达式"></el-input>
            </el-form-item>
            <el-form-item label="查询数量（limit）">
              <el-input-number v-model="mongoDBExpansionConfig.limit" :min="-1" :max="65535"
                               label="查询数量"></el-input-number>
            </el-form-item>
          </div>

        </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAddFetcherVisible = false">取 消</el-button>
          <el-button type="primary" @click="addFetcher">确 定</el-button>
        </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>

import {addFetcher, fetchFetcherConfig} from '@/api/engine/fetcherConfig'
import {fetchDatasourceConfigByType} from '@/api/engine/datasource'
import {ElMessage} from "element-plus";

export default {
  name: "BaseFetcherConfig",
  data() {
    return {
      dialogAddFetcherVisible: false,
      dialogAddFetcherTitle: "",
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      searchText: '',
      tableData: [],
      datasources: [],
      fetcherConfig: {},
      httpExpansionConfig: {
        url: "",
        method: "GET",
        headers: [{}],
        params: [{}],
        data: [{}],
        httpAuth: {
          username: "",
          password: ""
        }
      },
      mysqlExpansionConfig: {
        table: "",
        columnItems: [{}],
        condition: "",
        limit: -1
      },
      mongoDBExpansionConfig: {
        collection: "",
        condition: "",
        limit: -1
      }
    };
  },
  methods: {
    formatterType(row) {
      let label = ""
      switch (row.type) {
        case 1:
          label = "HTTP"
          break;
        case 2:
          label = "MySQL"
          break;
        case 3:
          label = "Redis"
          break;
        case 4:
          label = "MongoDB"
          break;
        default:
          label = "我不知道"
      }
      return label
    },
    handleSizeChange() {
      this.search()
    },
    handleCurrentChange() {
      this.search()
    },
    showHttpDialog() {
      this.dialogAddFetcherTitle = "HTTP"
      this.dialogAddFetcherVisible = true
      this.resetFetcherConfig()
      this.fetcherConfig.type = 1
      this.httpExpansionConfig = {
        url: "",
        method: "GET",
        headers: [{}],
        params: [{}],
        data: [{}],
        httpAuth: {
          username: "",
          password: ""
        }
      }
      this.fetchDatasource(1)
    },
    showMongoDBDialog() {
      this.dialogAddFetcherTitle = "MongoDB"
      this.dialogAddFetcherVisible = true
      this.resetFetcherConfig()
      this.fetcherConfig.type = 4
      this.mongoDBExpansionConfig = {
        collection: "",
        condition: "",
        limit: -1
      }
      this.fetchDatasource(4)
    },
    showMySQLDialog() {
      this.dialogAddFetcherTitle = "MySQL"
      this.dialogAddFetcherVisible = true
      this.resetFetcherConfig()
      this.fetcherConfig.type = 2
      this.mysqlExpansionConfig = {
        table: "",
        columnItems: [{}],
        condition: "",
        limit: -1
      }
      this.fetchDatasource(2)
    },
    resetFetcherConfig() {
      this.fetcherConfig = {
        name: "",
        description: "",
        datasource: "",
        estimatedExecutionTime: 1,
        type: 1,
        expansionConfig: "",
        defaultFetchMethod: 1
      }
    },
    fetchDatasource(type) {
      let that = this
      fetchDatasourceConfigByType(type).then(response => {
        that.datasources = response.data
      })
    },
    search: function () {
      let that = this
      fetchFetcherConfig(that.page.currentPage, that.page.pageSize).then(response => {
        that.tableData = response.data.dataList
        that.page.total = response.data.totalCount
      })
    },
    addFetcher() {
      let that = this

      // 校验逻辑
      if (!!!that.fetcherConfig.name) {
        ElMessage.error('名称不能为空');
        return
      }
      if (!!!that.fetcherConfig.description) {
        ElMessage.error('描述不能为空');
        return
      }

      let expansionConfig;
      let fetcherType = that.fetcherConfig.type
      let configValidator = null;
      switch (fetcherType) {
        case 1:
          // HTTP 校验逻辑
          configValidator = that.validateHttpConfig
          expansionConfig = that.httpExpansionConfig
          break
        case 2:
          // MySQL 校验逻辑
          configValidator = that.validateMySQLConfig
          expansionConfig = that.mysqlExpansionConfig
          break
        case 3:
          // Redis 校验逻辑
          break
        case 4:
          // Redis 校验逻辑
          configValidator = that.validateMongoDBConfig
          expansionConfig = that.mongoDBExpansionConfig
          break
      }

      if (configValidator == null) {
        ElMessage.error('错了哦，这是一条神奇的错误消息');
        return
      }

      let validateResult = configValidator(expansionConfig);
      if (!validateResult) {
        return
      }
      expansionConfig = JSON.stringify(expansionConfig)

      that.fetcherConfig.expansionConfig = expansionConfig

      addFetcher(that.fetcherConfig).then(response => {
        that.dialogAddFetcherVisible = false
        that.search()
        ElMessage.success('添加成功');
      }).catch(error => {
        console.info(error)
        ElMessage.error(error);
      })

    },
    validateHttpConfig(httpExpansionConfig) {
      return true
    },
    validateMySQLConfig(mysqlExpansionConfig) {
      return true
    },
    validateMongoDBConfig(expansionConfig) {
      return true
    },
    addHttpHeader(index) {
      this.httpExpansionConfig.headers.splice(index + 1, 0, {})
    },
    removeHttpHeader(index) {
      this.httpExpansionConfig.headers.splice(index, 1)
      if (this.httpExpansionConfig.headers.length === 0) {
        this.httpExpansionConfig.headers.push({})
      }
    },
    addMySQLField(index) {
      this.mysqlExpansionConfig.fields.splice(index + 1, 0, {})
    },
    removeMySQLField(index) {
      this.mysqlExpansionConfig.fields.splice(index, 1)
      if (this.mysqlExpansionConfig.fields.length === 0) {
        this.mysqlExpansionConfig.fields.push({})
      }
    }
  },
  mounted() {
    this.search()
  }
}
</script>

<style scoped>

</style>
